package com.zygame.sdk.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.zygame.sdk.utils.log.LogHelper;
import com.zygame.sdk.utils.phone.AppUtil;
import com.zygame.sdk.utils.phone.FileUtil;
import com.zygame.sdk.utils.phone.Phoneuitl;
import com.zygame.sdk.utils.res.ResourceUtil;

public class Icons {
	private static Icons downloadIcon = new Icons();

	private final static String TAG = "Icons";

	private final static int BUFFER = 4 * 1024;

	private static String savePath = AppUtil.getDownsPath() + "/icons/";

	private Icons() {
	}

	public static Icons getInstance() {
		if (downloadIcon == null) {
			synchronized (Icons.class) {
				if (downloadIcon == null) {
					downloadIcon = new Icons();
				}
			}
		}
		return downloadIcon;
	}

	/**
	 * 下载图标
	 */
	// public void startDownloadIcons(final String url,final DownloadCallBack
	// downloadCallBack) {
	//
	// final String filePath = AppUtil.getDownsPath() + getFileName(url);
	//
	// new Thread() {
	// @Override
	// public void run() {
	// FileOutputStream out = null;
	// InputStream input = null;
	// try {
	// URL iconsUrl = new URL(url);
	// HttpURLConnection conn = (HttpURLConnection) iconsUrl.openConnection();
	// conn.setReadTimeout(30 * 1000);
	// conn.setRequestMethod("GET");
	// if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
	// input = conn.getInputStream();
	// File file = new File(filePath);
	// if (!file.exists()) {
	// file.createNewFile();
	// }else{
	// file.delete();
	// }
	// out = new FileOutputStream(file);
	// byte[] buffer = new byte[BUFFER];
	// int length = 0;
	// while ((length = input.read(buffer)) != -1) {
	// out.write(buffer, 0, length);
	// }
	// out.flush();
	// out.close();
	// input.close();
	// LogHelper.i(TAG, "下载icons.zip成功");
	// }
	//
	// downloadCallBack.downloadSuccess("1"); //下载成功回调 1表示成功
	// } catch (Exception e) {
	// LogHelper.i(TAG, "下载icons.zip失败");
	// e.printStackTrace();
	// } finally {
	// if (out != null) {
	// try {
	// out.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// if (input != null) {
	// try {
	// input.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// }
	// // 解压zip文件
	// boolean flag = unzip(AppUtil.getDownsPath(), AppUtil.getDownsPath(),
	// getFileName(url));
	// if(flag){
	// LogHelper.i(TAG, "解压icons.zip成功");
	// }else{
	// LogHelper.i(TAG, "解压icons.zip失败");
	// }
	// }
	// }.start();
	// }

	/**
	 * 根据路径获取文件名
	 * 
	 * @author
	 * @date
	 * @return
	 */
	private static String getFileName(String path) {
		String filename = null;
		filename = path.substring(path.lastIndexOf('/') + 1);
		if (filename == null || "".equals(filename.trim())) {// 如果获取不到文件名称
			return null;
		}
		return filename;
	}

	/**
	 * @author Captain
	 * @param zipDirectory
	 *            压缩文件路径
	 * @param storageDirectory
	 *            解压文件路径
	 * @param fileName
	 *            压缩文件名（xxx.zip）
	 * @return
	 */
	public static boolean unzip(String zipDirectory, String storageDirectory, String zipFileName) {
		boolean result = false;
		String zipName = zipDirectory + zipFileName;
		String filePath = storageDirectory;
		ZipFile zipFile = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		File file = null;

		try {
			zipFile = new ZipFile(zipName);
			Enumeration<? extends ZipEntry> emu = zipFile.entries();
			while (emu.hasMoreElements()) {
				ZipEntry entry = (ZipEntry) emu.nextElement();
				if (entry.isDirectory()) {
					// 跳过mac系统文件
					if (entry.getName().contains("_MACOSX")) {
						continue;
					}
					File f = new File(filePath + entry.getName());
					f.mkdirs();
					savePath = filePath + entry.getName();
					continue;
				}
				bis = new BufferedInputStream(zipFile.getInputStream(entry));

				if (entry.getName().contains("_MACOSX")) {
					continue;
				} else {
					file = new File(filePath + entry.getName());
				}

				if (!file.exists()) {
					file.createNewFile();
				}
				File parent = file.getParentFile();

				if (parent != null && (!parent.exists())) {
					parent.mkdirs();
				}
				fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos, BUFFER);
				int count;
				byte data[] = new byte[BUFFER];
				while ((count = bis.read(data, 0, BUFFER)) != -1) {
					bos.write(data, 0, count);
				}
				bos.flush();
				// 把图片保存到集合里
				// saveToMap(savePath,getFileName(entry.getName()));
			}

			bos.close();
			bis.close();
			zipFile.close();
			result = true;
		} catch (Exception e) {
			LogHelper.i(TAG, "解压icon.zip失败");
			e.printStackTrace();
			result = false;
		} finally {
			try {
				if (null != bos) {
					bos.close();
				}
				if (null != bis) {
					bis.close();
				}
				if (null != zipFile) {
					zipFile.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				result = false;
			}
		}
		return result;
	}

	/**
	 * 根据名字获取图片
	 * 
	 * @param iconName
	 *            图片名字
	 * @param type
	 *            图片类型：0：没选中 1：选中
	 * @return
	 */
	public Bitmap getIcons(Context context, String iconName, int type) {
		if (TextUtils.isEmpty(iconName)) {
			return null;
		}
		if (type == 1) { // select的图片
			iconName = getSelectName(iconName);
		}
		File file = new File(savePath + iconName);

		if (file.exists()) {
			FileInputStream input = null;
			try {
				input = new FileInputStream(file);
				byte[] data = FileUtil.readInputStream(input);
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				if (bitmap != null) {
					return bitmap;
				}
			} catch (FileNotFoundException e) {
				LogHelper.i(TAG, "获取图片失败");
				e.printStackTrace();
			}
		} else { // 读取drawable里的图片
			iconName = deleteIconSuffix(iconName);
			Bitmap b = BitmapFactory.decodeResource(context.getResources(), ResourceUtil.getDrawableId(context, iconName));
			return b;
		}
		return null;
	}

	/**
	 * 
	 * @param iconName
	 * @param type
	 *            图片类型：0：没选中 1：选中
	 * @param scalX
	 *            屏幕宽度
	 * @param scalY
	 *            屏幕高度
	 * @return
	 */
	public Bitmap getIconsFromScreen(Context context, String iconName, int type) {

		Bitmap bitmap = null;
		if (TextUtils.isEmpty(iconName)) {
			return null;
		}
		if (type == 1) { // select的图片
			iconName = getSelectName(iconName);
		}

		HashMap<String, Bitmap> hm = AppUtil.getBitmapCache();
		if (hm.containsKey(iconName)) {
			// Toast.makeText(context, "bitmap的图片名：" + iconName,
			// Toast.LENGTH_SHORT).show();
			return hm.get(iconName);
		}

		File file = new File(savePath + iconName);
		if (file.exists()) {
			FileInputStream input = null;
			try {
				input = new FileInputStream(file);
				byte[] data = FileUtil.readInputStream(input);
				bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				if (bitmap != null) {
					Bitmap b = Phoneuitl.bitmapAdaptive(context, bitmap, 1);
					// Toast.makeText(context, "下载的图片名：" + iconName,
					// Toast.LENGTH_SHORT).show();
					hm.put(iconName, b);
					return b;
				}
			} catch (FileNotFoundException e) {
				LogHelper.i(TAG, "获取图片失败");
				e.printStackTrace();
			}
		} else { // 读取drawable里的图片
			iconName = deleteIconSuffix(iconName);
			bitmap = BitmapFactory.decodeResource(context.getResources(), ResourceUtil.getDrawableId(context, iconName));
			Bitmap b = Phoneuitl.bitmapAdaptive(context, bitmap, 2);

			return b;
		}
		return null;
	}

	public Bitmap getIconsFromDrawable(Context context, String iconName, int type) {

		Bitmap bitmap = null;
		if (TextUtils.isEmpty(iconName)) {
			return null;
		}
		if (type == 1) { // select的图片
			iconName = getSelectName2(iconName);
		}

		// 读取drawable里的图片
		iconName = deleteIconSuffix2(iconName);
		bitmap = BitmapFactory.decodeResource(context.getResources(), ResourceUtil.getDrawableId(context, iconName));
		Bitmap b = Phoneuitl.bitmapAdaptive(context, bitmap, 2);
		return b;
	}

	/**
	 * 根据名字获取图片
	 * 
	 * @param iconName
	 *            图片名字
	 * @param type
	 *            图片类型：0：没选中 1：选中
	 * @return
	 */
	public Bitmap getIcons(String path) {
		if (TextUtils.isEmpty(path)) {
			return null;
		}
		File file = new File(path);
		if (file.exists()) {
			FileInputStream input = null;
			try {
				input = new FileInputStream(file);
				byte[] data = FileUtil.readInputStream(input);
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				if (bitmap != null) {
					return bitmap;
				}
			} catch (FileNotFoundException e) {
				LogHelper.i(TAG, "获取图片失败");
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 获取select的图片
	 * 
	 * @param iconName
	 * @return
	 */
	private String getSelectName(String iconName) {
		String[] arr = iconName.split("\\.");
		iconName = arr[0] + "_s." + arr[1];
		if (iconName == null || "".equals(iconName.trim())) {// 如果获取不到文件名称
			return null;
		}
		return iconName;
	}

	private String deleteIconSuffix(String iconName) {
		String[] arr = iconName.split("\\.");
		if (arr[0].contains("fy_d_")) {
			return arr[0];
		}
		
		return "fy_d_" + arr[0];
	}
	
	private String getSelectName2(String iconName) {
		String[] arr = iconName.split("\\.");
		if (arr[0].contains("fy_d_new_s_")) {
			return arr[0];
		}
		
		return "fy_d_new_s_" + arr[0];
	}

	private String deleteIconSuffix2(String iconName) {
		String[] arr = iconName.split("\\.");
		if (arr[0].contains("fy_d_new_")) {
			return arr[0];
		}
		
		return "fy_d_new_" + arr[0];
	}
}
